# app_controller.py
from PySide6.QtCore import QObject, Signal, Slot, QTimer
from typing import Dict, Type
from dataclasses import dataclass

@dataclass
class ProjectData:
    """全局数据模型，真实业务里换成你的图网表、器件库等"""
    selected_uuid: str = ""

class AppController(QObject):
    _instance = None

    # 全局信号枢纽
    selection_changed = Signal(str)          # 任何窗口选中器件
    request_open    = Signal(str, dict)      # 窗口请求打开另一窗口

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self):
        if hasattr(self, "_inited"):
            return
        super().__init__()
        self._inited = True
        self.project = ProjectData()
        self.windows: Dict[str, "QMainWindow"] = {}
        self._window_counter = 0

        # 把信号连到自己
        self.request_open.connect(self._on_open_window)

    # ---------------- 窗口工厂 ----------------
    def open_initial_windows(self):
        """启动时默认打开哪些窗，可配置"""
        self._on_open_window("schematic", {})
        self._on_open_window("pcb", {})

    @Slot(str, dict)
    def _on_open_window(self, klass_name: str, kwargs: dict):
        # 懒加载，避免循环 import
        if klass_name == "schematic":
            from schematic_window import SchematicWindow
            cls: Type = SchematicWindow
        elif klass_name == "pcb":
            from pcb_window import PcbWindow
            cls = PcbWindow
        else:
            return

        uid = f"{klass_name}_{self._window_counter}"
        self._window_counter += 1
        w = cls(uid, self)          # 把 controller 引用传进去
        w.destroyed.connect(lambda: self._on_window_closed(uid))
        self.windows[uid] = w
        w.show()

    def _on_window_closed(self, uid: str):
        self.windows.pop(uid, None)
        if not self.windows:
            # 所有主窗都关了
            from PySide6.QtWidgets import QApplication
            QApplication.instance().quit()